/*
 * $Id: QELogWindowController.m 84 2009-07-12 03:54:50Z jon@bway.net $
 * Chalk
 *
 * Created 4/21/09
 * Copyright Jon Gordon
 * 
 * Permission is hereby granted, free of charge, to any person obtaining 
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including 
 * without limitation the rights to use, copy, modify, merge, publish, 
 * distribute, sublicense, and/or sell copies of the Software, and to 
 * permit persons to whom the Software is furnished to do so, subject to 
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#import "QELogWindowController.h"

#import "QEBand.h"
#import "QEMode.h"


@implementation QELogWindowController
#pragma mark LIFECYCLE METHODS
- (id)init
{
    return [super initWithWindowNibName:@"LogWindow"];
} // init

- (void)windowDidLoad
{
    NSLog(@"MESSAGE: %s", __PRETTY_FUNCTION__);
    
    [[self window] setDelegate:self];
    
    // make sure that the QSOs table shows the time in UTC
    NSTimeZone *utc = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    NSDateFormatter *cf = [[[NSDateFormatter alloc] init] autorelease];
    [cf setFormatterBehavior:NSDateFormatterBehavior10_4];
    [cf setTimeZone:utc];
    [cf setDateFormat:@"yyyy-MM-dd"];
    [cf setLenient:YES];
    NSTableColumn *dateColumn = [qsosTable tableColumnWithIdentifier:@"qso_date"];
    [[dateColumn dataCell] setFormatter:cf];
    [[dateField cell] setFormatter:cf];
    
    cf = [[[NSDateFormatter alloc] init] autorelease];
    [cf setFormatterBehavior:NSDateFormatterBehavior10_4];
    [cf setTimeZone:utc];
    [cf setDateFormat:@"HHmm"];
    [cf setLenient:YES];
    NSTableColumn *timeColumn = [qsosTable tableColumnWithIdentifier:@"qso_time_on"];
    [[timeColumn dataCell] setFormatter:cf];
    
    NSDateFormatter *timeFieldFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [timeFieldFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [timeFieldFormatter setTimeZone:utc];
    [timeFieldFormatter setDateFormat:@"HHmm"];
    [timeFieldFormatter setLenient:YES];
    [[timeField cell] setFormatter:timeFieldFormatter];
    
    // the log window has a UTC clock that updates in real time
    NSDateFormatter *clockLabelFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [clockLabelFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [clockLabelFormatter setTimeZone:utc];
    [clockLabelFormatter setDateFormat:@"dd-MMM-yyyy HH:mm:ss"];
    [[clockLabel cell] setFormatter:clockLabelFormatter];
    [clockLabel setObjectValue:[NSDate date]];
    
    clockTimer = [NSTimer scheduledTimerWithTimeInterval:0.29
                                                  target:self
                                                selector:@selector(clockUpdate:)
                                                userInfo:nil
                                                 repeats:YES];
    
    // set the content for various controllers and other outlets
    NSSortDescriptor *modeNameSortDescriptor =
    [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [modesController setContent:[[QEMode allModes] 
                                 sortedArrayUsingDescriptors:[NSArray arrayWithObject:modeNameSortDescriptor]]];
    [rcvModesController setContent:[[QEMode allModes] 
                                    sortedArrayUsingDescriptors:[NSArray arrayWithObject:modeNameSortDescriptor]]];
    [modeNameSortDescriptor release];
    
    NSSortDescriptor *bandNameSortDescriptor =
    [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [bandsController setContent:[[QEBand allBandsAsArray] 
                                 sortedArrayUsingDescriptors:[NSArray arrayWithObject:bandNameSortDescriptor]]];
    [bandNameSortDescriptor release];
        
    // BEGIN DEBUG
    NSLog(@"  current selection in QSOs array controller: %@",
          [qsosController selection]);
    NSLog(@"  selected objects: %@", [qsosController selectedObjects]);
    NSLog(@"  [selectedObjects count]: %lu", ((unsigned long) [[qsosController selectedObjects] count]));
} // windowDidLoad

- (void)windowWillClose:(NSNotification *)notification
{
    NSLog(@"MESSAGE: %s", __PRETTY_FUNCTION__);
    [clockTimer invalidate];
} // windowWillClose:

- (void)clockUpdate:(NSTimer *)theTimer
{
    [clockLabel setObjectValue:[NSDate date]];
} // clockUpdate

- (IBAction)newQSOAction:(id)sender
{
    NSLog(@"MESSAGE: %s", __PRETTY_FUNCTION__);
    
    /*
     * This is taken from the example at the end of Chapter 9
     * in Hillegass, PROGRAMMING FOR MAC OS X, 3rd ed.
     */
    NSWindow *w = [qsosTable window];
    
    // try to end any editing that is taking place
    BOOL editingEnded = [w makeFirstResponder:w];
    if (!editingEnded) {
        NSLog(@"  failed to end editing");
        return;
    } // if
    NSUndoManager *undo = [[self document] undoManager];
    
    // has an edit occurred already in this event?
    if ([undo groupingLevel]) {
        // close the last group
        [undo endUndoGrouping];
        // open a new group
        [undo beginUndoGrouping];
    } // if
    
    // create the object
    id newQSOEntity = [qsosController newObject];
    
    // add it to the QSOs content array
    [qsosController addObject:newQSOEntity];
    [newQSOEntity release];
    
    // re-sort
    [qsosController rearrangeObjects];
    
    // get the sorted array
    NSArray *a = [qsosController arrangedObjects];
    
    // find the object just added
    int row = [a indexOfObjectIdenticalTo:newQSOEntity];
    NSLog(@"  starting edit of %@ in row %d", newQSOEntity, row);
    
    // begin the edit in the first column
    [qsosTable editColumn:0
                      row:row
                withEvent:nil
                   select:YES];
}// newQSOAction:


- (NSArrayController *)qsosController
{
    return [[qsosController retain] autorelease];
} // qsosController
@end
